#include "DepthRenderTarget.h"

DepthRenderTarget::DepthRenderTarget(unsigned int width, unsigned int height, unsigned int ratio) {
	width_ = width;
	height_ = height;
	ratio_ = ratio;
/*

	glGenTextures(1, &col_textureID_);
	glBindTexture(GL_TEXTURE_2D, col_textureID_);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexImage2D(
		GL_TEXTURE_2D,
		0,
		GL_RGBA8,
		width_,
		height_,
		0,
		GL_RGBA8,
		GL_UNSIGNED_BYTE,
		0);
*/
	glGenTextures(1, &dep_textureID_);
	glBindTexture(GL_TEXTURE_2D, dep_textureID_);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	//glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);

	glTexImage2D(
		GL_TEXTURE_2D,
		0,
		GL_DEPTH_COMPONENT,
		width_ * ratio_,
		height_ * ratio_,
		0,
		GL_DEPTH_COMPONENT,
		GL_UNSIGNED_BYTE,
		0);



	glGenFramebuffersEXT(1, &frameBufferID_);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBufferID_);
/*
	glFramebufferTexture2DEXT(
		GL_FRAMEBUFFER_EXT,
		GL_COLOR_ATTACHMENT0_EXT,
		GL_TEXTURE_2D,
		col_textureID_,
		0);
*/
	glFramebufferTexture2DEXT(
		GL_FRAMEBUFFER_EXT,
		GL_DEPTH_ATTACHMENT_EXT,
		GL_TEXTURE_2D,
		dep_textureID_,
		0);

	glDrawBuffer(GL_NONE);
	glReadBuffer(GL_NONE);// you can comment this out and see
	if (GL_FRAMEBUFFER_COMPLETE_EXT != glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT)) {
		printf("Invalid framebuffer configuration\n");
		//exit(-1);
	}
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	glDrawBuffer(GL_BACK);
	glBindTexture(GL_TEXTURE_2D, 0);
}

DepthRenderTarget::~DepthRenderTarget() {
	glDeleteFramebuffersEXT(1, &frameBufferID_);
	glDeleteRenderbuffersEXT(1, &depthBufferID_);
	glDeleteTextures(1, &col_textureID_);
	glDeleteTextures(1, &dep_textureID_);
}

GLuint DepthRenderTarget::colorTextureID() const {
	return col_textureID_;
}

GLuint DepthRenderTarget::depthTextureID() const {
	return dep_textureID_;
}

void DepthRenderTarget::bind() {
	//glPushAttrib(GL_VIEWPORT_BIT);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBufferID_);
	glDrawBuffer(GL_NONE);
	glViewport(0, 0, width_ * ratio_, height_ * ratio_);
}

void DepthRenderTarget::unbind() {
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	glViewport(0, 0, width_, height_);
	glDrawBuffer(GL_BACK);
	//glPopAttrib();
}
